package com.uzai.console.service.tb.tbexclusivegoods.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.RegularUtil;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.tb.tbexclusivegoods.*;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.TbExclusiveGoodsMapper;
import com.uzai.console.mapper.TbTokenMapper;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.tb.tbexclusivegoods.TbExclusiveGoodsService;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.tb.tbexclusivegoods.TbExclusiveGoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
@Slf4j
public class TbExclusiveGoodsServiceImpl implements TbExclusiveGoodsService {

    @Autowired
    private TbExclusiveGoodsMapper tbExclusiveGoodsMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 分页查询淘宝定向商品列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return TbExclusiveGoodsVo
     */
    public Page<TbExclusiveGoodsVo> findTbExclusiveGoodsList(TbExclusiveGoodsQuery tbExclusiveGoodsQuery){
        //新建返回到页面的LIST对象
        List<TbExclusiveGoodsVo> tbExclusiveGoodsVoList = new ArrayList<>();
        //返回到页面分页对象
        Page<TbExclusiveGoodsVo> pageVo = new Page<>();

        //执行分页查询对象
        Page<TbExclusiveGoods> page = new Page<>();
        tbExclusiveGoodsQuery.convert(page);
        List<TbExclusiveGoods> tbExclusiveGoodsList = tbExclusiveGoodsMapper.findByList(page, tbExclusiveGoodsQuery);

        if(tbExclusiveGoodsList != null){
            for (TbExclusiveGoods tbExclusiveGoods : tbExclusiveGoodsList){
                TbExclusiveGoodsVo tbExclusiveGoodsInfoVo = new TbExclusiveGoodsVo();
                BeanUtils.copyProperties(tbExclusiveGoods, tbExclusiveGoodsInfoVo);

                if(tbExclusiveGoods.getTokenId() != null){
                    TbToken tbToken = tbTokenMapper.selectById(tbExclusiveGoods.getTokenId(), tbExclusiveGoods.getMerId());
                    if(tbToken != null){
                        tbExclusiveGoodsInfoVo.setTokenName(tbToken.getUserName());
                    }
                }

                tbExclusiveGoodsVoList.add(tbExclusiveGoodsInfoVo);
            }
        }
        BeanUtils.copyProperties(page, pageVo);

        pageVo.setRecords(tbExclusiveGoodsVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询淘宝定向商品详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public TbExclusiveGoodsVo findTbExclusiveGoods(TbExclusiveGoodsIdDto tbExclusiveGoodsIdDto){

        if(tbExclusiveGoodsIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        TbExclusiveGoods tbExclusiveGoods = tbExclusiveGoodsMapper.selectById(tbExclusiveGoodsIdDto.getId(), tbExclusiveGoodsIdDto.getMerId());
        if(tbExclusiveGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝定向商品不存在");
        }

        TbExclusiveGoodsVo tbExclusiveGoodsInfoVo = new TbExclusiveGoodsVo();
        BeanUtils.copyProperties(tbExclusiveGoods, tbExclusiveGoodsInfoVo);

        if(tbExclusiveGoods.getTokenId() != null){
            TbToken tbToken = tbTokenMapper.selectById(tbExclusiveGoods.getTokenId(), tbExclusiveGoods.getMerId());
            if(tbToken != null){
                tbExclusiveGoodsInfoVo.setTokenName(tbToken.getUserName());
            }
        }

        return tbExclusiveGoodsInfoVo;
    }


    /**
     * 添加淘宝定向商品详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbExclusiveGoodsDto
     * @return null
     */
    @Transactional
    public void addTbExclusiveGoods(TbExclusiveGoodsDto tbExclusiveGoodsDto){

        String itemId = tbExclusiveGoodsDto.getItemId();
        if(StringUtils.isBlank(itemId)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品id");
        }

        String[] itemIdList = itemId.split("-");
        if(itemIdList == null  || itemIdList.length  != 2){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id格式不正确");
        }

        if(StringUtils.isBlank(tbExclusiveGoodsDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品名称");
        }

        if(tbExclusiveGoodsDto.getNormalCommissionRate() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择普通佣金率");
        }

        if(tbExclusiveGoodsDto.getExclusiveCommissionRate() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定向佣金率");
        }

        if(tbExclusiveGoodsDto.getStartTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择开始时间");
        }

        if(tbExclusiveGoodsDto.getEndTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择结束时间");
        }

        TbExclusiveGoods tbExclusiveGoods = tbExclusiveGoodsMapper.selectByItemIdSuffix(itemIdList[1], tbExclusiveGoodsDto.getMerId());
        if(tbExclusiveGoods != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该商品已经存在");
        }

        tbExclusiveGoods = new TbExclusiveGoods();
        Integer now = DateUtil.getNowTime();
        tbExclusiveGoods.setId(IdWorker.getId());
        tbExclusiveGoods.setCreateTime(now);
        tbExclusiveGoods.setUpdateTime(now);
        tbExclusiveGoods.setMerId(tbExclusiveGoodsDto.getMerId());
        tbExclusiveGoods.setName(tbExclusiveGoodsDto.getName());
        tbExclusiveGoods.setImgUrl(tbExclusiveGoodsDto.getImgUrl());
        tbExclusiveGoods.setItemId(itemId);
        tbExclusiveGoods.setItemIdSuffix(itemIdList[1]); //获取商品id的后段
        tbExclusiveGoods.setNormalCommissionRate(tbExclusiveGoodsDto.getNormalCommissionRate());
        tbExclusiveGoods.setExclusiveCommissionRate(tbExclusiveGoodsDto.getExclusiveCommissionRate());
        tbExclusiveGoods.setStartTime(tbExclusiveGoodsDto.getStartTime());
        tbExclusiveGoods.setEndTime(tbExclusiveGoodsDto.getEndTime());
        tbExclusiveGoods.setTokenId(tbExclusiveGoodsDto.getTokenId());

        //保存
        tbExclusiveGoodsMapper.insertSelective(tbExclusiveGoods);

    }

    /**
     * 修改淘宝定向商品详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbExclusiveGoodsDto
     * @return null
     */
    @Transactional
    public void updateTbExclusiveGoods(TbExclusiveGoodsDto tbExclusiveGoodsDto){

        if(tbExclusiveGoodsDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        if(tbExclusiveGoodsDto.getNormalCommissionRate() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择普通佣金率");
        }

        if(tbExclusiveGoodsDto.getExclusiveCommissionRate() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定向佣金率");
        }

        if(tbExclusiveGoodsDto.getStartTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择开始时间");
        }

        if(tbExclusiveGoodsDto.getEndTime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择结束时间");
        }

        Integer now = DateUtil.getNowTime();

        TbExclusiveGoods tbExclusiveGoods = tbExclusiveGoodsMapper.selectById(tbExclusiveGoodsDto.getId(), tbExclusiveGoodsDto.getMerId());
        if(tbExclusiveGoods == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该定向商品不存在");
        }

        tbExclusiveGoods.setNormalCommissionRate(tbExclusiveGoodsDto.getNormalCommissionRate());
        tbExclusiveGoods.setExclusiveCommissionRate(tbExclusiveGoodsDto.getExclusiveCommissionRate());
        tbExclusiveGoods.setStartTime(tbExclusiveGoodsDto.getStartTime());
        tbExclusiveGoods.setEndTime(tbExclusiveGoodsDto.getEndTime());
        tbExclusiveGoods.setTokenId(tbExclusiveGoodsDto.getTokenId());
        tbExclusiveGoods.setUpdateTime(now);

        //保存
        tbExclusiveGoodsMapper.updateByIdSelective(tbExclusiveGoods);

    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbExclusiveGoodsIdListDto
     * @return null
     */
    @Transactional
    public void deleteTbExclusiveGoods(TbExclusiveGoodsIdListDto tbExclusiveGoodsIdListDto){

        List<Long> idList = tbExclusiveGoodsIdListDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        for (Long id : idList){
            //删除活动
            tbExclusiveGoodsMapper.deleteById(id, tbExclusiveGoodsIdListDto.getMerId());
        }
    }

    /**
     * 获取定向商品信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbExclusiveGoodsTurnLinkDto
     * @return null
     */
    public SimpleTurnlinkVo getGoodInfo(TbExclusiveGoodsTurnLinkDto tbExclusiveGoodsTurnLinkDto){
        if(StringUtils.isBlank(tbExclusiveGoodsTurnLinkDto.getContent())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品链接/淘口令");
        }
        //获取系统默认的联盟
        Long defaultTbTokenUserId = uzaiConsoleSysConfig.getDefaultTbTokenUserId();
        if(defaultTbTokenUserId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未配置默认联盟账号");
        }
        TbToken tbToken = tbTokenMapper.selectByUserIdAndTurnLink(defaultTbTokenUserId, 0); //从返利中查询默认系统默认联盟
        if(tbToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未找到默认配置的联盟账号");
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new  SimpleTurnLinkDto();
        int tbQueryType = RegularUtil.getTbQueryType(tbExclusiveGoodsTurnLinkDto.getContent());
        if(tbQueryType == 1){
            simpleTurnLinkDto.setUrl(tbExclusiveGoodsTurnLinkDto.getContent());
        }else if(tbQueryType == 2){
            simpleTurnLinkDto.setItemId(tbExclusiveGoodsTurnLinkDto.getContent());
        }else if(tbQueryType == 3){
            simpleTurnLinkDto.setPwd(tbExclusiveGoodsTurnLinkDto.getContent());
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未识别到商品信息");
        }
        simpleTurnLinkDto.setTokenId(tbToken.getId());
        simpleTurnLinkDto.setPid(tbToken.getDefPid());
        simpleTurnLinkDto.setGenerateShortUrl(0); //不生成
        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);
        log.info("---淘宝定向商品调用淘宝转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));

        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            return uzaiRespVo.getData();
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品解析信息失败");
        }
    }

}
